var paginationTotal = 1;// 记录总<{$lang.quantity}>
$(function() {
//	initData(0); // 初始化分页<{$lang.quantity}>据
	clear();
	$("#add").dialog({
				autoOpen : false,
				width : 400,
				modal : true,
				show : "slide",
				buttons : {
					'<{$lang.ok}>' : function() {
						save();
					},
					'<{$lang.cancel}>' : function() {
						$(this).dialog('close');
					}
				}
			});

	$("#package").dialog({
				autoOpen : false,
				width : 400,
				modal : true,
				show : "slide",
				buttons : {
					'<{$lang.ok}>' : function() {
						packagesave();
					},
					'<{$lang.cancel}>' : function() {
						$(this).dialog('close');
					}
				}
			});
	$("#batchAdd").dialog({
				autoOpen : false,
				width : 500,
				modal : true,
				show : "slide",
				buttons : {
					'<{$lang.ok}>' : function() {
						if($('[name=productFile]').val()==""){
							$(".batchAddTips").html("<{$lang.select}><{$lang.file}>");
						}else{
							$("#batchAddBtn").click();							
						}
					},
					'<{$lang.cancel}>' : function() {
						$(this).dialog('close');
					}
				}
			});

	// 删除
	$("#right_confirm").dialog({
		autoOpen : false,
		modal : true,
		height : 'auto',
		show : "slide",
		buttons : {
			'<{$lang.ok}>' : function() {
				$('#message').text("");
				loading();
				$.ajax({ // 这里使用到Jquery的ajax方法
					type : "POST",
					async : false,
					dataType : "json",
					url : "/product/product/update-status", // 请求的处理url
					data : {
						'product_id' : Uid,
						'product_status' : Ustatus
					},
					success : function(json) {
						closeLoading();
						if (json.ask == 1) {// <{$lang.operation}><{$lang.success}>

							$('#alert_msg p').html(json.msg);
							$('#alert_msg').dialog('open');
							loadData(paginationCurrentPage, paginationPageSize);
						} else {
							$('#alert_msg p').text("<{$lang.operation}><{$lang.fail}>");
							$('#alert_msg').dialog('open');
						}
					}
				});
				$(this).dialog('close');
			},
			'<{$lang.cancel}>' : function() {
				$(this).dialog('close');
			}
		}

	});

	// 弹出提示
	$("#alert_msg").dialog({
				autoOpen : false,
				modal : true,
				width : 600,
				show : "slide",
				buttons : {
					'<{$lang.close}>' : function() {
						$(this).dialog('close');
					}
				}

			});
	$("#printDialog").dialog({
				autoOpen : false,
				modal : true,
				width : 500,
				show : "slide",
				buttons : {
					"OK" : function() {
						$("#printForm").submit();
						var dialog = $(this);
						setTimeout(function(){
							dialog.dialog("close");
						},1000);
					},
					"Close" : function() {
						$(this).dialog("close");
					}
				}
			});
	$(".checkAll").live("click", function() {
				if (typeof $(".checkAll").attr("checked") == "string") {
					$(".checkProduct").attr("checked", true);
				} else {
					$(".checkProduct").attr("checked", false);
				}

			});

	//回车处理
	$("#customer_id").add("#sproduct_sku").keyup(function(e){
		var key = e.which;
		if(key==13){
			initData(0);
		}
	});

    //按货架打印
    $("#printShelfProudctDialog").dialog({
        autoOpen : false,
        modal : true,
        width : 650,
        show : "slide",
        buttons : {
            "OK" : function() {
                $("#PrintProductForm").submit();
                $("#printDialog").dialog("close");
                $(".checkShelf").attr("checked", false);
                $(".checkAll").attr("checked", false);
            },
            "Close" : function() {
                $(this).dialog("close");
            }
        }
    });
});
function loadData(page, pageSize) {
	var product_sku = $('[name=sproduct_sku]').val();
	     product_sku=product_sku.replace('—','-');
	var customer_id = $('[name=customer_id]').val();
    var product_ref_sku=$('[name=product_ref_sku]').val();
	loading();
	$.ajax({ // 这里使用到Jquery的ajax方法
		type : "POST",
		async : false,
		dataType : "json",
		url : "/product/product/list", // 请求的处理url
		data : {
			'page' : page, // 分页的页<{$lang.quantity}>
			'pageSize' : pageSize,
			'product_sku' : product_sku,
            'product_ref_sku' : product_ref_sku,
			'customer_id' : customer_id
		},
		success : function(json) {
			var list = '';
			if (json.ask != 1) {
				list += "<tr>";
				list = "<td colspan='12' class=''>&nbsp;<{$lang.no_data}></td>";
				list += "</tr>";
			} else {
				paginationTotal = json.count;
				$(".checkAll").attr("checked", false);
				$.each(json.result, function(key, val) {
					var cla = key % 2 == 0 ? "" : "even-tr";
					list += "<tr class='" + cla + "' id='product_"
							+ val.product_id + "'>";
					list += "<td><input type='checkbox' value='"
							+ val.product_id
							+ "' class='checkProduct' name='checkPoduct[]'></td>";
					list += "<td>" + (key+1) + "</td>";
					list += '<td><span onclick="productEdit('+val.product_id+',false)">' + val.customer_id + '—'+val.product_sku + '</span></td>';
					list += "<td>" + val.customer_id + "</td>";
					list += "<td>" + val.product_title + "</td>";
					list += "<td>" + val.product_category + "</td>";
					list += "<td>" + val.product_length + "/"
							+ val.product_width + "/" + val.product_height
							+ "</td>";

					list += "<td>" + val.product_weight + "kg</td>";
					list += "<td>" + val.product_declared_value + "</td>";
					list += "<td>" + val.product_packect_type + "</td>";
					list += "<td>" + val.product_date_added + "</td>";
					list += "<td>" + val.product_status + "</td>";

					list += "<td>";
					list += "<a href=\"javascript:editProduct("
							+ val.product_id
							+ ");\" title='<{$lang.edit}>'><img alt='<{$lang.edit}>' src='/images/icon/edit.gif'></a>";
					list += "<a href=\"javascript:packageProduct("
							+ val.product_id
							+ ");\" title='<{$lang.package}>'><{$lang.package}></a>";
					list += "</td>";

					list += "</tr>";
					

					if(val.wp&&val.has_wpb==1){
						list += "<tr>";
						list += "<td style='padding: 0;' colspan='13'><table width='100%'";
						list += "cellspacing='0' cellpadding='0' border='0'>";
						list += "<tbody>";
						$.each(val.wp, function(i, v) {
							list += "<tr class='even-tr'>";
							list += "<td width='3%'>&nbsp;</td>";
							list += "<td width='20%'><{$lang.ws_code}>："+v.ws_code+"</td>";
							list += "<td width='10%'><{$lang.useable}><{$lang.quantity}>："+v.wp_quantity+"</td>";
							list += "<td width='10%'><{$lang.hold}><{$lang.quantity}>："+v.wp_quantity_hold+"</td>";
							list += "<td><{$lang.status}>："+(v.wp_status==1?'<{$lang.useable}>':'<{$lang.unuseable}>')+"</td>";
							list += "</tr>";
							if(v.wpb){
								$.each(v.wpb, function(j, v1) {
									list += "<tr class='even-tr'>";
									list += "<td width='3%'>&nbsp;</td>";
									list += "<td width='20%'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<{$lang.product}><{$lang.batch}>wpb_id："+v1.wpb_id+"</td>";
									list += "<td width='10%'><{$lang.useable}><{$lang.quantity}>："+v1.wpb_quantity+"</td>";
									list += "<td width='10%'><{$lang.hold}><{$lang.quantity}>："+v1.wpb_quantity_hold+"</td>";
									list += "<td><{$lang.status}>："+(v1.wpb_status==1?'<{$lang.useable}>':'<{$lang.unuseable}>')+"</td>";
									list += "</tr>";						
									
								});
							}
						});	
					
						list += "</tbody>";
						list += "</table>";
						list += "</td>";
						list += "</tr>";
					}
				});
			}
			$("#list").html(list);
			closeLoading();
		}
	});
}

function search() {
	initData(0);
}


function productEdit(id,edit){//<{$lang.product}><{$lang.edit}>		
	window.open("/product/product/view-product-info/productId/"+id+"/edit/"+edit+"/"+new Date(),"_blank");
}

function editProduct(id) {
	clear();
	if (id) {
		$.ajax({
			type : "POST",
			async : false,
			dataType : "json",
			url : "/product/product/single", // 请求的处理url
			data : {
				'product_id' : id
			},
			success : function(json) {
				if (json.ask == 1) {
					var val = json.result;
					var div = "";
						
					$.each(json.options, function(i, o_v) {
							
						div+= "<div class='item'><span class='userInfoLeft'>"+o_v.po_name+":</span>" +
							"<span class='userInfoRight'>" ;
							
						if(o_v.po_choose_type==0){							
							var options = "<select style='width: 200px; display: inline;' name='po_select["+o_v.po_id+"]' value='' class='autoGenerate' type='text'>";

							$.each(o_v.product_option_choose, function(poc, pocv) {
	
								options += '<option value="' + pocv.poc_id + '"';								
									if (pocv.poc_id == o_v.poc_id) {
										options += ' selected';										
									}

								options += '>' + pocv.poc_value + '</option>';
								
							});	
							options += "</select>" ;
							div+=options;
						}else{
							var po_value = o_v.po_value;
							var input = "<input type='text' class='text ui-widget-content ui-corner-all' value='"+po_value+"'  name='po_input["+o_v.po_id+"]'>";
							div+=input;
						}				
						div+="</span>" +
							"<div style='clear:both;'></div>" +
							"</div>";
						
					});
												
					div+= "<div class='item'><span class='userInfoLeft'><{$lang.customer_code}>:</span><span class='userInfoRight'><input type='text' name='customer_id' value='"+val.customer_id+"' readonly class='text ui-widget-content ui-corner-all' style='background:#ddd;'/></span><div style='clear: both;'></div></div>";			
//					div+= "<input type='text' name='customer_id' value='"+val.customer_id+"' readonly class='text ui-widget-content ui-corner-all'/>";
//					alert(options+json.result.pov[0].po_id);		
					
									
					$("#product_option").html(div);
					$('[name=product_id]').val(val.product_id);
					$('[name=product_name]').val(val.product_title);
					$('[name=product_sku]').val(val.product_sku);
					$('[name=product_length]').val(val.product_length);
					$('[name=product_width]').val(val.product_width);

					$('[name=product_height]').val(val.product_height);
					$('[name=product_weight]').val(val.product_weight);
					$('[name=product_net_weight]').val(val.product_net_weight);
					$('[name=product_price]').val(val.product_declared_value);
					
					$("#add").dialog("open");
				} else {								
					$('#alert_msg p').text(json.result);
					$('#alert_msg').dialog('open');
				}
			}
		});
	} else {
		clear();
		$.ajax({
			type : "POST",
			async : false,
			dataType : "json",
			url : "/product/product/option", // 请求的处理url
			data : {
				'product_id' : id
			},
			success : function(json) {
				if (json.ask == 1) {
					var val = json.result;
					var div = "";				
					$.each(json.options, function(i, o_v) {					
						div+= "<div class='item'><span class='userInfoLeft'>"+o_v.po_name+":</span>" +
							"<span class='userInfoRight'>" ;					
						if(o_v.po_choose_type==0){							
							var options = "<select style='width: 200px; display: inline;' name='po_select["+o_v.po_id+"]' value='' class='autoGenerate' type='text'>";
		
							$.each(o_v.product_option_choose, function(poc, pocv) {
		
								options += '<option value="' + pocv.poc_id + '"';						
		
								options += '>' + pocv.poc_value + '</option>';
								
							});	
							options += "</select>" ;
							div+=options;
						}else{
							var input = "<input type='text' class='text ui-widget-content ui-corner-all'   name='po_input["+o_v.po_id+"]'>";
							div+=input;
						}				
						div+="</span>" +
							"<div style='clear:both;'></div>" +
							"</div>";
						
					});	
					div+= "<div class='item'><span class='userInfoLeft'><{$lang.customer_code}>:</span><span class='userInfoRight'><input type='text' name='customer_id' value=''  class='text ui-widget-content ui-corner-all'/></span><div style='clear: both;'></div></div>";
					$("#product_option").html(div);
				} 
			}
		});
		$("#add").dialog("open");
	}
}

function packageProduct(id){
	clear();
	$('[name=warehouseid]').html("");
	$("[name=packageid]").html("");
	loading();
	$.ajax({
		type : "POST",
		async : false,
		dataType : "json",
		url : "/product/product/package", // 请求的处理url
		data : {
			'product_id' : id
		},
		success : function(json) {
			closeLoading();
			if (json.ask == 1) {
				var val = json.result;
				var div = "";	
				var wareHtml = "";
				$.each(json.warehouse, function(i, wh) {//仓库
					var sel = json.packageMap&&json.packageMap.warehouse_id==wh.warehouse_id?"selected":"";
					wareHtml+="<option value='"+wh.warehouse_id+"' "+sel+">"+wh.warehouse_name+"</option>";					
				});	
				
				$("[name=product_id]").val(id);
				if(json.packageMap&&json.packageMap.ppm_id){
					$("[name=ppm_id]").val(json.packageMap.ppm_id);					
				}
				$('[name=warehouseid]').html(wareHtml);
				
				$('[name=warehouseid]').change(function(){//<{$lang.package}>
					var packageHtml = "<option value='0' ><{$lang.select}></option>";
					var index = $('[name=warehouseid] option').index($('[name=warehouseid] option:selected'));
//					alert(index);
					$.each(json.warehouse[index].packages,function(i,p){
						var sel = json.packageMap&&json.packageMap.package_id==p.pp_id?"selected":"";
						packageHtml+="<option value='"+p.pp_id+"' "+sel+">"+p.pp_name+"</option>";
					})
					$("[name=packageid]").html(packageHtml);
				}).change();
			} 
		}
	});
	$("#package").dialog("open");
}
function printProduct(printType) {
	clear();
	if ($(".checkProduct:checked").size()) {
		var html = "<form action='print-label' method='post' id='printForm' target='_blank'>";
		html += '<input type="hidden" name="type" value="'+printType+'">';
		html += '<table width="100%" cellspacing=3 cellpadding=3  border=1>';
		html += '<tr class="row height25 row-header" style="background:#ddd;">';
		html += '<td class="per20  cell" sortColumn="productName">SKU Name</td>';
		html += '<td class="per20 cell" sortColumn="sku">SKU</td>';
		html += '<td class="per20 cell " sortColumn="status">Status</td>';
		html += '<td class="per20 cell">Category</td>';
		html += '<td class="per15 cell no-background">Qty</td>';
		html += '</tr>';

		$(".checkProduct:checked").each(function() {
			var select_product = $(this).parent().parent();
			html += '<tr class="row height25">';
			html += '<td class="per20  cell" sortColumn="productName">'
					+ select_product.find("td:eq(2)").text() + '</td>';
			html += '<td class="per20 cell" sortColumn="sku">'
					+ select_product.find("td:eq(3)").text() + '</td>';
			html += '<td class="per20 cell " sortColumn="status">'
					+ select_product.find("td:eq(11)").text() + '</td>';
			html += '<td class="per20 cell">'
					+ select_product.find("td:eq(5)").text() + '</td>';
			html += '<td class="per15 cell no-background"><input type="text" class="width1" value="1" size=3 name="count'
					+ select_product.find(".checkProduct").val() + '"/></td>';
			html += '</tr>';

		});

		html += '</table>';
		html += "</form>";
		$("#printDialog").html(html).dialog("open");
	} else {
		$('#alert_msg p').text("<{$lang.select}><{$lang.product}>");
		$('#alert_msg').dialog('open');
	}
}

function batchAddProduct(){
	$(".batchAddTips").html("");
	$('#batchAdd').dialog('open');
}
function updateProductStatus(status, op) {
	if ($(".checkProduct:checked").size() < 1) {
		$('#alert_msg p').text("<{$lang.select}><{$lang.product}>");
		$('#alert_msg').dialog('open');
		return false;
	}
	var ids = "";
	$(".checkProduct:checked").each(function() {
				var select_product = $(this).parent().parent();
				ids += select_product.find("td:eq(1)").text() + ",";

			});

	Uid = ids;
	Ustatus = status;
	$('#right_confirm p').text("<{$lang.ok}>" + op + "？");
	$('#right_confirm').dialog('open');
}

function save() {
	vForm = '';
	vForm = $("#createForm").serializeArray();
//	alert(vForm);return;
	var tip = '';
	$.ajax({
		type : "POST",
		async : false,
		dataType : "json",
		url : "/product/product/update", // 请求的处理url
		data : vForm,
		success : function(json) {
			if (json.ask) {
				tip = '<{$lang.operation}><{$lang.success}>';
				$("#add").dialog("close");
				$('#alert_msg p').text(tip);
				$('#alert_msg').dialog('open');
				loadData(paginationCurrentPage, paginationPageSize);
			} else {
				tip = json.result.message;
			}
//			$("#add").dialog("close");
			$('#tips').html(tip);
		}
	});
}

function packagesave() {
//	alert($("[name=packageid] option:selected").val());
	var pForm = $("#packageForm").serializeArray();
	if($("[name=packageid] option:selected").val()==""||$("[name=packageid] option:selected").val()=="0"){
		$(".packageTips").html("<{$lang.select}><{$lang.package}>");
		return;
	}
//	alert(vForm);return;
	var tip = '';
	$.ajax({
		type : "POST",
		async : false,
		dataType : "json",
		url : "/product/product/package-map-save", // 请求的处理url
		data : pForm,
		success : function(json) {
			if (json.ask) {
				tip = '<{$lang.operation}><{$lang.success}>';
				$("#package").dialog("close");
				$('#alert_msg p').text(tip);
				$('#alert_msg').dialog('open');
				initData(paginationCurrentPage-1); 
			} else {
				tip = '<{$lang.operation}><{$lang.success}>';
			}
//			$("#add").dialog("close");
			$('.packageTips').html(tip);
		}
	});
}

function closebox() {
	$("#add").dialog("close");
}

// 删除
function delelteInfo(id) {
	if (id == '' || id == undefined) {
		return false;
	}
	Uid = id;
	$('#right_confirm').dialog('open');
}

function clear() {
	$(".validateTips").text("");
	$(".packageTips").text("");
	$("#product_option").html("");
	$('[name=product_id]').val("");
	$('[name=product_name]').val("");
	$('[name=product_sku]').val("");
	$('[name=product_length]').val("");
	$('[name=product_width]').val("");

	$('[name=product_height]').val("");
	$('[name=product_weight]').val("");
	$('[name=product_net_weight]').val("");
	$('[name=product_price]').val("");
}



function PrintShelfProduct(printType) {
    if ($(".checkProduct:checked").size()) {
        var vForm = $("[name='checkPoduct[]']").serialize();
        $.ajax({
            url: "/product/product/get-shelf-product",
            async: false,
            dataType: "json",
            type:"post",
            data:vForm,
            success: function(json) {
                if(json.ask=='1'){
                    var html = "<form action='/warehouse/shelf/print-product-label' method='post' id='PrintProductForm' target='_blank'>";
                    html += '<input type="hidden" name="type" value="'+printType+'">';
                    html += '<table class="myTab" width="100%" cellspacing=3 cellpadding=3  border=1>';
                    html += '<tr >';
                    html += '<th ><{$lang.ws_code}></th>';
                    html += '<th >SKU</td>';
                    html += '<th >Category</th>';
                    html += '<th class="no-background">Qty</th>';
                    html += '</tr>';
                    $.each(json.result,function(i,val){
                        html += '<tr>';
                        html += '<td>'+val.ws_code+'</td>';
                        html += '<td>'+(val.customer_id + '-' +val.product_sku)+'</td>';
                        html += '<td>'+val.category+'</td>';
                        html += '<td><input type="text" class="width1" value="'+val.quantity+'" size=3 name="'+val.ws_code+'#productid#'+val.product_id+'"></td>';
                        html += '</tr>';
                    });

                    html += '</table>';
                    html += "</form>";
                    $("#printShelfProudctDialog").html(html).dialog("open");
                }else{
                    alertTip("<{$lang.print_ws_code_not_exists}>");
                }
            }
        });

    } else {
        alertTip("<{$lang.select}><{$lang.product}>");
        return false;
    }
}
//<{$lang.operation}>提示
function alertTip(tip) {
    $('<div title="<{$lang.tip}>(<{$lang.close}><{$lang.esc}>)"><p align="center">' + tip + '</p></div>').dialog({
        width: 300,
        modal: true,
        show:"slide",
        buttons: {
            '<{$lang.close}>': function() {
                $(this).dialog('close');
            }
        },
        close:function(){

        }
    });
}